# -*- coding: utf-8 -*-
__author__ = 'hftec'
#实时图像数据服务器子线程
import threading, time,simplejson
#import Server

json_cmd={
    "cmd":1,
    "phi":[],
    "model":0,
    "filename":[],
    "resp_code":0
}


class TcpThread:

    def __init__(self,client,backqueue):#backqueue将每个线程收到的数据反向传给总的控制进程
        self.client = client
        self.run = True
        self.backqueue = backqueue
        self.tcp_data = threading.Thread(target = self.wait_data)
        # self.serial_data = threading.Thread(target = self.wait_serial_data)
        self.tcp_data.start()
        # self.serial_data.start()

    def wait_data(self):
        try:
            while(self.run):
                try:
                    data = self.client.recv(512)
                    if data == '':
                        return
                    print "data",data

                    try:
                        cmd_json = simplejson.loads(data)
                        self.backqueue.put({"client":self.client,"cmd":cmd_json})
                        # json_cmd["cmd"] = cmd_json["cmd"]
                        # if json_cmd["cmd"] == 1:  #计算角度
                        #
                        #     if(self.uphi.is_exit(cmd_json["filename"][0])):
                        #        if( self.uphi.load_uphi(cmd_json["filename"][0]) <0):
                        #             json_cmd["resp_code"] = 202      #文件存在问题
                        #             self.tcp.send(simplejson.dumps(json_cmd))
                        #             continue
                        #        cal.calculate_cmd(cmd_json)
                        #     else:
                        #         json_cmd["resp_code"] = 201    #文件不存在
                        #         self.tcp.send(simplejson.dumps(json_cmd))
                        # SerialComunicate.serial.write(data_hex)
                    except Exception,e:
                        print "json loads error ",e
                except:
                    return

        except KeyboardInterrupt:
            self.tcp.close()
            return

    def close(self):
        self.run = False
